package com.xyh.transaction.schedule;

import com.xyh.transaction.common.OrderStatus;
import com.xyh.transaction.entity.Goods;
import com.xyh.transaction.entity.OrderDetail;
import com.xyh.transaction.mapper.GoodsMapper;
import com.xyh.transaction.mapper.OrderDetailMapper;
import com.xyh.transaction.mapper.OrderMapper;
import com.xyh.transaction.queue.OrderDelayQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Collection;
import java.util.List;

@Slf4j
@Configuration
@EnableScheduling
public class OrderDelayQueueScheduler {

    @Autowired
    private OrderDelayQueue orderDelayQueue;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Scheduled(fixedDelay = 1000) // 每隔 1 秒执行一次
    public void processExpiredOrders() {
        Collection<String> expiredOrders = orderDelayQueue.getExpiredOrders();
        if (expiredOrders.isEmpty()) {
            return;
        }

        expiredOrders.forEach(expiredOrder -> {
            try {
                String[] split = expiredOrder.split("_");
                Integer orderId = Integer.valueOf(split[0]);

                // 恢复库存
                List<OrderDetail> orderDetails = orderDetailMapper.findByOrderId(orderId);
                orderDetails.forEach(orderDetail -> {
                    Goods goods = goodsMapper.findById(orderDetail.getGoodsId());
                    Goods updateGoods = new Goods();
                    updateGoods.setId(orderDetail.getGoodsId());
                    updateGoods.setStock(goods.getStock() + orderDetail.getCount().intValue());
                    goodsMapper.update(updateGoods);
                    log.info("恢复商品【{}】库存", goods.getName());
                });

                // 更新订单状态
                orderMapper.updateStatusById(OrderStatus.CANCELLED, orderId);
                orderDelayQueue.removeProcessedOrder(expiredOrder);
                log.info("订单【{}】未付款，已过期自动取消！", split[1]);

            } catch (Exception e) {
                log.error("处理过期订单【{}】时发生错误: {}", expiredOrder, e.getMessage());
            }
        });
    }

}
